#include "scripteditor.h"

ScriptEditor::ScriptEditor(QWidget *parent) :
    QTextEdit(parent)
{
    QFont font;
    font.setFamily("Courier");
    font.setStyleHint(QFont::Monospace);
    font.setFixedPitch(true);
    font.setPointSize(10);

    setFont(font);

    QFontMetrics metrics(font);
    setTabStopWidth(4 * metrics.width(' '));

    m_highlighter = new Highlighter(this->document());
    m_currentFile = "";

    m_dirty = false;

    c=0;

}

void ScriptEditor::setDirty(bool value){
    bool old = m_dirty;
    m_dirty = value;

    if(value!=old){
        emit dirtyChanged(value);
    }
}


void ScriptEditor::loadScript(const QString &fileName){
    QFile file(fileName);
    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QTextStream ts(&file);
    setPlainText(ts.readAll());
    m_currentFile = fileName;
    file.close();
    connect(this,SIGNAL(textChanged()),this, SLOT(setDirty()));
}

bool ScriptEditor::saveScript(){
    QFile file(m_currentFile);
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
        return false;

    QTextStream ts(&file);
    ts << this->toPlainText();
    file.close();

    setDirty(false);
}

void ScriptEditor::setDirty(){
    setDirty(true);
}

void ScriptEditor::setCompleter(QCompleter *completer)
 {

     if (c)
         QObject::disconnect(c, 0, this, 0);

     c = completer;

     if (!c)
         return;

     c->setWidget(this);
     c->setCompletionMode(QCompleter::PopupCompletion);
     c->setCaseSensitivity(Qt::CaseSensitive);
     QObject::connect(c, SIGNAL(activated(QString)),
                      this, SLOT(insertCompletion(QString)));

 }

 QCompleter *ScriptEditor::completer() const
 {
     return c;
 }

 void ScriptEditor::insertCompletion(const QString& completion)
 {

     if (c->widget() != this)
         return;
     QTextCursor tc = textCursor();
     int extra = completion.length() - c->completionPrefix().length();
     tc.movePosition(QTextCursor::Left);
     tc.movePosition(QTextCursor::EndOfWord);
     tc.insertText(completion.right(extra));
     setTextCursor(tc);
 }

 QString ScriptEditor::textUnderCursor() const
 {
     QTextCursor tc = textCursor();
     tc.select(QTextCursor::WordUnderCursor);
     return tc.selectedText();
 }

 void ScriptEditor::focusInEvent(QFocusEvent *e)
 {
     if (c)
         c->setWidget(this);
     QTextEdit::focusInEvent(e);
 }

 void ScriptEditor::keyPressEvent(QKeyEvent *e)
 {
     if (c && c->popup()->isVisible()) {
         // The following keys are forwarded by the completer to the widget
        switch (e->key()) {
        case Qt::Key_Enter:
        case Qt::Key_Return:
        case Qt::Key_Escape:
        case Qt::Key_Tab:
        case Qt::Key_Backtab:
             e->ignore();
             return; // let the completer do default behavior
        default:
            break;
        }
     }

     bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_Space); // CTRL+E
     if (!c || !isShortcut) // do not process the shortcut when we have a completer
         QTextEdit::keyPressEvent(e);

     const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
     if (!c || (ctrlOrShift && e->text().isEmpty())){
         return;
     }

     static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word
     bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;
     QString completionPrefix = textUnderCursor();



     if (!isShortcut && (hasModifier || e->text().isEmpty()|| completionPrefix.length() < 3
                       || eow.contains(e->text().right(1)))) {
         c->popup()->hide();

         return;
     }

     if(!isShortcut)
         return;


     if (completionPrefix != c->completionPrefix()) {
         c->setCompletionPrefix(completionPrefix);
         c->popup()->setCurrentIndex(c->completionModel()->index(0, 0));
     }
     QRect cr = cursorRect();
     cr.setWidth(c->popup()->sizeHintForColumn(0)
                 + c->popup()->verticalScrollBar()->sizeHint().width());
     c->complete(cr); // popup it up!

 }
